package com.mall.web.control.app.pay;

import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.mall.common.util.bit.PropertiesConfigure;
import com.mall.constant.PropertiesKey;
import com.mall.vo.WeixinUserInfo;
import com.mall.web.annotation.UserLoginMessage;
import com.mall.web.util.HttpUtil;
import com.tencent.common.Configure;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/wxuser/")
public class GetWeiXinUserInfoController {
	
	private static final Logger log = LoggerFactory.getLogger(GetWeiXinUserInfoController.class);
	@Autowired
	private PropertiesConfigure propertiesConfigure;

	/**
	 * 鉴权成功后返回页面地址
	 */
	private  String AUTH_RETURN_URI= "http://www.zhiwangvip.com/wxuser/index.json";

	/**
	 * 支付完成异步通知接口地址
	 */
	private static String PAY_NOTIFY_URL;
	

	/**
	 * 鉴权请求地址模板
	 */
	private static final String REDIRECT_URL_TPL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect";

	/**
	 * 回调通知处理成功后返回给微信的消息
	 */
	private static final String SUCCESS_MSG = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";

	/**
	 * 获取access_token接口地址
	 */
	private static final String ACCESS_TOKEN_API_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
	
	
	
	
	/**
	 * 授权请求
	 * 
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("auth")
	@UserLoginMessage
	public String auth( HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) throws Exception {
		log.error("开始授权请求...");
		// 将订单ID先保存在session中，待授权完成后继续取出使用
		log.error("pay>sessionId:{}", request.getSession().getId());
		String redirectUrl = String.format(REDIRECT_URL_TPL, Configure.getAppid(),
				URLEncoder.encode(AUTH_RETURN_URI, "utf-8"), null);
		log.error("redirectTo:{}", redirectUrl);
		return "redirect:" + redirectUrl;
	}
	
	
	
	
	

	public static WeixinUserInfo getUserInfo(String accessToken, String openId) {
		 WeixinUserInfo weixinUserInfo = null;
	        // 拼接请求地址
	        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
	        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
	        // 获取用户信息
	        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                weixinUserInfo = new WeixinUserInfo();
                // 用户的标识
                weixinUserInfo.setOpenId(jsonObject.getString("openid"));
                // 关注状态（1是关注，0是未关注），未关注时获取不到其余信息
                weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe"));
                // 用户关注时间
                weixinUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time"));
                // 昵称
                weixinUserInfo.setNickname(jsonObject.getString("nickname"));
                // 用户的性别（1是男性，2是女性，0是未知）
                weixinUserInfo.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                weixinUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                weixinUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                weixinUserInfo.setCity(jsonObject.getString("city"));
                // 用户的语言，简体中文为zh_CN
                weixinUserInfo.setLanguage(jsonObject.getString("language"));
                // 用户头像
                weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
            } catch (Exception e) {
                if (0 == weixinUserInfo.getSubscribe()) {
                    log.error("用户{}已取消关注", weixinUserInfo.getOpenId());
                } else {
                    int errorCode = jsonObject.getInt("errcode");
                    String errorMsg = jsonObject.getString("errmsg");
                    log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
                }
            }
        }
        return weixinUserInfo;
    }
	
	@RequestMapping("index")
	@ResponseBody
	public String index(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        // 获取接口访问凭证
       // String accessToken = CommonUtil.getToken("wx2aa52d84161cbfaa", "684653d2da192bccfef454e3ac47e587").getAccessToken();
		Map<String, String[]> params = request.getParameterMap();// 针对get获取get参数
		String[] codes = params.get("code");// 拿到的code的值
		String code = codes[0];// code
		// 获取用户openid
		String authResponse = HttpUtil.sendGet(ACCESS_TOKEN_API_URL,
				String.format("appid=%s&secret=%s&code=%s&grant_type=authorization_code", Configure.getAppid(),
						Configure.getAppSecret(), code));
		com.alibaba.fastjson.JSONObject authResponseJson = JSON.parseObject(authResponse);
		log.error("用户authInfo:" + authResponseJson.toString());
     	Integer errcode = authResponseJson.getInteger("errcode");
     	if (errcode != null && errcode != 0) {
     		log.error("请求用户authInfo失败,errcode:{}", errcode);
     		return null; // TODO 跳转到error页
     	}
     	String openid = authResponseJson.getString("openid");
     //   WeixinUserInfo user = getUserInfo(accessToken, "oej0xuKlOqzpY4y9MMNWbIqfKjnE");
//       
//        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";
//        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", "oej0xuKlOqzpY4y9MMNWbIqfKjnE");
//        JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
//        
//       System.out.println(jsonObject);
//
//        System.out.println("OpenID：" + user.getOpenId());
//        System.out.println("关注状态：" + user.getSubscribe());
//        System.out.println("关注时间：" + user.getSubscribeTime());
//        System.out.println("昵称：" + user.getNickname());
//        System.out.println("性别：" + user.getSex());
//        System.out.println("国家：" + user.getCountry());
//        System.out.println("省份：" + user.getProvince());
//        System.out.println("城市：" + user.getCity());
//        System.out.println("语言：" + user.getLanguage());
//        System.out.println("头像：" + user.getHeadImgUrl());
		return openid;
		
    }
	
	
	
	
	
	
	
	
	

}
